package com.example.demo.service.Impl;

import com.example.demo.entity.Borrow;
import com.example.demo.entity.UserHistory;
import com.example.demo.mapper.BookMapper;
import com.example.demo.mapper.BorrowMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.BorrowBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BorrowBookServiceImpl implements BorrowBookService {
    @Autowired
    BorrowMapper borrowMapper;
    @Autowired
    BookMapper bookMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public List<UserHistory> myHistory(int id) {
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//        System.out.println(df.format(new Date()));
        List<UserHistory> list = borrowMapper.myHistory(id);
        System.out.println(list);
        return list;
    }

    @Override
    public List<Object> borrowHistory() {
        return null;
    }

    @Override
    public boolean borrowBook(String username, int bookId) {
            //查询库存是否为0
        if(bookMapper.selectByPrimaryKey(bookId).getStock()>0){
            System.out.println("stock>0");
            int id = userMapper.getUserIdByUsername(username);
            String uid = String.valueOf(id);
            System.out.println("uid+++"+uid);
            //借阅时间
            java.util.Date date = new java.util.Date();
            java.sql.Date sqlDate = new java.sql.Date(date.getTime());
            System.out.println(sqlDate);
            //添加借书记录  borrow表
            Map<Object,Object> map = new HashMap();
            map.put("uid",uid);
            map.put("borrowTime",sqlDate);
            map.put("bid",bookId);

            borrowMapper.borrowBook(map);
            System.out.println(uid);
            System.out.println(sqlDate);
            System.out.println(bookId);

            //库存-1
            bookMapper.decreaseStock(bookId);
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean backBook(int borrowId) {
        Map<Object,Object> map = new HashMap();
        java.util.Date date = new java.util.Date();
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());
        map.put("backTime",sqlDate);
        map.put("borrowId",borrowId);
        borrowMapper.backBook(map);

        //库存+1
        int bookId = borrowMapper.getBookId(borrowId);
        bookMapper.increaseStock(bookId);
        return true;
    }
}
